package com.noah.project.controller

import com.noah.project.global.Const
import com.noah.project.model.Reply
import org.slf4j.LoggerFactory
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.ResponseBody
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.multipart.MultipartFile
import java.io.File
import java.io.IOException

@RestController
class UploadApiController {
    val log = LoggerFactory.getLogger(UploadApiController::class.simpleName)

    /**
     * 实现文件上传
     */
    @RequestMapping(Const.API_UPLOAD)
    @ResponseBody
    fun upload(@RequestParam(Const.UPLOAD_FILE) file: MultipartFile): Reply {
        if (file.isEmpty) {
            return Reply(code = Const.FAIL_NONE, msg = "文件为空")
        }
        // 获取文件名
        val fileName = file.originalFilename
        // 文件上传路径
        var filePath = Const.IMG_PATH_WIN
        if(System.getProperty("os.name").contains("Linux")){
            filePath = Const.IMG_PATH_LINUX
        }
        // 解决中文问题，liunx下中文路径，图片显示问题
        // fileName = UUID.randomUUID() + suffixName;
        val dest = File(filePath + fileName)
        log.info("上传文件:${dest.absolutePath}")
        // 检测是否存在目录
        if (!dest.parentFile.exists()) {
            dest.parentFile.mkdirs()
        }
        try {
            file.transferTo(dest)
            return Reply(code = Const.SUCCESS, msg = "上传成功",data = fileName)
        } catch (e: IllegalStateException) {
            e.printStackTrace()
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return Reply(code = Const.FAIL, msg = "上传失败")
    }

}